package cn.adkii.springframework.beans.factory.support;

import cn.adkii.springframework.beans.BeansException;
import cn.adkii.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author malingdi
 * @description JDK实例化
 * @date 2023/11/20 19:40
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        Class clazz = beanDefinition.getClass();
        try {
            if (null != ctor){
                return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            }else {
                return clazz.getDeclaredConstructor().newInstance();
            }
        }catch (NoSuchMethodException | InstantiationException| IllegalAccessException | InvocationTargetException e){
            throw new BeansException("Failed to instantiate ["  + clazz.getName() + "]", e);
        }
    }
}
